package org.loneranger.p2_bean_post_processor.bean;

import org.loneranger.p2_bean_post_processor.annotation.BeanName;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * 实现BeanPostProcessor，是一个bean的后置处理器
 * 该后置处理器不是针对某一个bean的，而是针对所有bean
 *
 * @author LoneRanger
 */
@Component
public class BeanNamePostProcessor implements BeanPostProcessor {

	/**
	 * 初始化后 将@BeanName的值放到被注解的属性上
	 *
	 * @param bean
	 * @param beanName
	 * @return
	 * @throws BeansException
	 */
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		if (beanName.equals("userService")) {
			Class<?> clazz = bean.getClass();
			for (Field field : clazz.getDeclaredFields()) {
				if (field.isAnnotationPresent(BeanName.class)) {
					String value = field.getAnnotation(BeanName.class).value();

					field.setAccessible(true);
					try {
						field.set(bean, value);
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return bean;
		//return null; 如果这里传入null，那么其他的BeanPostProcessor 无法获取bean ，getBean也会获取null
	}
}
